package com.happok.onlineclass.usermanagement.authentication.service;

import cn.hutool.core.bean.BeanUtil;
import com.happok.onlineclass.usermanagement.user.dataobject.UserDO;
import com.happok.onlineclass.usermanagement.authentication.dto.UserDetailsDTO;
import com.happok.onlineclass.usermanagement.user.service.UserDaoService;
import com.happok.onlineclass.usermanagement.user.service.UserPermissionDaoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * 接口分类
 * 功能说明
 *
 * @author : chenac
 * @module 项目名称/模块名          yapi 项目组/子项目
 * @date : 2021/6/28 12:14
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserDaoService userDaoService;

    @Autowired
    private UserPermissionDaoService userPermissionDaoService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDetailsDTO userDetailsDTO = new UserDetailsDTO();
        UserDO userDo = userDaoService.getUserByUsername(username);
        if (ObjectUtils.isEmpty(userDo)) {
            try {
                userDo = userDaoService.getUserDetailById(Integer.valueOf(username));
            } catch (Exception e) {
                throw new UsernameNotFoundException("用户名或密码错误");
            }
        }
        BeanUtil.copyProperties(userDo, userDetailsDTO);
        userDetailsDTO.setEnterpriseAuthorityMap(userPermissionDaoService.getEnterpriseAuthorities(userDo.getId()));
        userDetailsDTO.setPlatformAuthoritys(userPermissionDaoService.getPlatformAuthorities(userDo.getId()));
        userDetailsDTO.setTrainOrgAuthorityMap(userPermissionDaoService.getTrainOrgAuthorities(userDo.getId()));
        return userDetailsDTO;
    }
}
